/**
 * Example 3: 
 * 
 * It is important to note that pageContext, session, and application objects can be accessed from a tag class. 
 * This means that attributes from any and all of the different scopes can be used in a tag class.
 * 
 * -> the class should extend javax.servlet.jsp.tagext.BodyTagSupport
 * -> should override the method called public int doStartTag() throws JspTagException
 * -> can override the method public void doInitBody() throws JspTagException
 * -> needs the method public int doAfterBody() throws JspTagException
 * -> should override the method called public int doEndTag() throws JspTagException
 * -> does not need to override the public void release() method
 * -> the bodycontent tag in the tag descriptor library should be JSP
 * 
 */
package com.wang.taglib;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class HelloScopeTaglib extends BodyTagSupport{

	private static final long serialVersionUID = 3759732203517766812L;
	
	int count = 1;
    int loop = 1;
    
    public void setLoopNumber(String loopNumber)
    {
    	loop = Integer.valueOf(loopNumber);
    }

	public String getGreeting()
	{
		return "Loop greeting";
	}

	public int doStartTag() throws JspException
	{
		try
		{
			JspWriter out = pageContext.getOut();
			out.write(getGreeting());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return EVAL_BODY_BUFFERED;
	}
	
	public void doInitBody() throws JspException
	{  
		try{  
			bodyContent.write("<br>");
			bodyContent.newLine();
		}
		catch(IOException e){  
			e.printStackTrace();  
		}
	}
	
	public int doAfterBody() throws JspException
	{
		try
		{
			if(count < loop)
			{
				BufferedReader br = new BufferedReader(getBodyContent().getReader());
				StringBuilder contents = new StringBuilder();
				try {
			        String line = null;
			        while (( line = br.readLine()) != null){
			          contents.append(line);
			          contents.append(System.getProperty("line.separator"));
			        }
			      }
			      finally {
			        br.close();
			      }
				
				bodyContent.append("<BR>");
				bodyContent.newLine();
				count++;
				return EVAL_BODY_BUFFERED;
			}

        	bodyContent.writeOut(getPreviousOut());
        	bodyContent.newLine();
			count = 1;
		} 
		catch (IOException e1) {
			e1.printStackTrace();
		}
		
		return SKIP_BODY;
    }
	
	public int doEndTag() throws JspException
	{
		return EVAL_PAGE;
	}
}
